package com.ruoyi.feike.service.impl;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.feike.domain.*;
import com.ruoyi.feike.domain.vo.AnnualReviewyHistoryVO;
import com.ruoyi.feike.domain.vo.ParkingLocationVO1;
import com.ruoyi.feike.mapper.*;
import com.ruoyi.feike.service.ITierCashDepositService;
import org.activiti.api.process.model.ProcessInstance;
import org.activiti.api.process.model.builders.ProcessPayloadBuilder;
import org.activiti.api.process.runtime.ProcessRuntime;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * feikeService业务层处理
 *
 * @author ruoyi
 * @date 2022-08-02
 */
@Service
public class TierCashDepositServiceImpl implements ITierCashDepositService {
    @Autowired
    private TierCashDepositMapper tierCashDepositMapper;

    @Autowired
    private AnnualReviewyMapper annualReviewyMapper;

    @Autowired
    private ParkingLocationRegistrationMapper parkingLocationRegistrationMapper;

    @Autowired
    private ParkingLocationMapper parkingLocationMapper;

    @Autowired
    private DealerInformationMapper dealerInformationMapper;

    @Autowired
    private PlmMapper plmMapper;

    @Autowired
    private ProcessRuntime processRuntime;

    @Autowired
    private TaskService taskService;

    @Autowired
    private RuntimeService runtimeService;

    /**
     * 查询feike
     *
     * @param id feikeID
     * @return feike
     */
    @Override
    public Map<String, Object> selectTierCashDepositById(String id) {
        Map<String, Object> map = new HashMap<>();
        AnnualReviewy annualReviewy = annualReviewyMapper.selectAnnualReviewyById(id);
        if (annualReviewy!=null){
            TierCashDeposit tierCashDeposit = tierCashDepositMapper.selectTierCashDepositById(annualReviewy.getId());

            String parkinglocation1 = tierCashDeposit.getParkinglocations();
            if (!StringUtils.isEmpty(parkinglocation1)){
                boolean contains = parkinglocation1.contains(",");
                if (contains){
                    String[] split = parkinglocation1.split(",");
                    tierCashDeposit.setParkinglocationList(split);
                }
            }

            map.put("id", annualReviewy.getId());
            map.put("instanceId", annualReviewy.getInstanceId());
            map.put("type", annualReviewy.getType());
            map.put("title", annualReviewy.getTitle());
            map.put("state", annualReviewy.getState());
            map.put("create_name", annualReviewy.getCreateName());
            map.put("create_by", annualReviewy.getCreateBy());
            map.put("create_time", annualReviewy.getCreateTime());
            map.put("update_time", annualReviewy.getUpdateTime());
            map.put("data", tierCashDeposit);
        }

        return map;
    }

    @Override
    public Map<String, Object> selectTierCashDepositByInstanceId(String instanceId) {
        Map<String, Object> map = new HashMap<>();
        AnnualReviewy annualReviewy = annualReviewyMapper.selectAnnualReviewyByInstanceId(instanceId);
        if (annualReviewy!=null){
            TierCashDeposit tierCashDeposit = tierCashDepositMapper.selectTierCashDepositById(annualReviewy.getId());

            String parkinglocation1 = tierCashDeposit.getParkinglocations();
            if (!StringUtils.isEmpty(parkinglocation1)){
                boolean contains = parkinglocation1.contains(",");
                if (contains){
                    String[] split = parkinglocation1.split(",");
                    tierCashDeposit.setParkinglocationList(split);
                }
            }

            map.put("id", annualReviewy.getId());
            map.put("instanceId", annualReviewy.getInstanceId());
            map.put("type", annualReviewy.getType());
            map.put("title", annualReviewy.getTitle());
            map.put("state", annualReviewy.getState());
            map.put("create_name", annualReviewy.getCreateName());
            map.put("create_by", annualReviewy.getCreateBy());
            map.put("create_time", annualReviewy.getCreateTime());
            map.put("update_time", annualReviewy.getUpdateTime());
            map.put("data", tierCashDeposit);
        }

        return map;
    }

    /**
     * 查询feike列表
     *
     * @param tierCashDeposit feike
     * @return feike
     */
    @Override
    public List<TierCashDeposit> selectTierCashDepositList(TierCashDeposit tierCashDeposit) {
        return tierCashDepositMapper.selectTierCashDepositList(tierCashDeposit);
    }

    /**
     * 新增feike
     *
     * @param tierCashDeposit feike
     * @return 结果
     */
    @Override
    public int insertTierCashDeposit(TierCashDeposit tierCashDeposit) {
        System.out.println("tierCashDeposit新增对象： " + tierCashDeposit);
        String instanceId = IdUtils.simpleUUID();
        String id = instanceId;
        String title = SecurityUtils.getLoginUser()
                                    .getUser()
                                    .getNickName() + "-" + "2nd-tier cash deposit流程";
        Authentication.setAuthenticatedUserId(SecurityUtils.getLoginUser()
                                                           .getUser()
                                                           .getUserId()
                                                           .toString());
        ProcessInstance processInstance = processRuntime.start(ProcessPayloadBuilder
                .start()
                .withProcessDefinitionKey("tierCashDeposit")
                .withName(title)
                .withBusinessKey(instanceId)
                // .withVariable("deptLeader",join)
                .build());

        Task task = null;
        task = taskService.createTaskQuery()
                          .processInstanceId(processInstance.getId())
                          .singleResult();
        TaskQuery query = taskService.createTaskQuery()
                                     .taskCandidateOrAssigned(SecurityUtils.getUsername())
                                     .active();
        List<Task> todoList = query.list();//获取申请人的待办任务列表
        for (Task tmp : todoList) {
            if (tmp.getProcessInstanceId()
                   .equals(processInstance.getId())) {
                task = tmp;//获取当前流程实例，当前申请人的待办任务
                break;
            }
        }
        HashMap<String, Object> variables = new HashMap<String, Object>();
        // List<Map<String, Object>> actForm = (List<Map<String, Object>>) map.get("actForm");
        // for (Map<String, Object> form : actForm) {
        //     variables.put(String.valueOf(form.get("controlId")), form.get("controlValue"));
        // }
        variables.put("toUnderwriter", 0);
        taskService.complete(task.getId(), variables);

        // 对 ParkingLocation表 的 Dealer Code 做更新操作      根据经销商名称和位置做查询
        // ParkingLocation parkingLocation = parkingLocationMapper.selectParkingLocationByDealerAndParkingLocation(tierCashDeposit.getDealerNameCn(),tierCashDeposit.getParkingLocation());
        // if(parkingLocation!=null){
        //     parkingLocation.setDealercode(tierCashDeposit.getDealerCode());
        //     parkingLocationMapper.updateParkingLocation(parkingLocation);
        // }

        // 对 plm表 的 2nd-tier deposit receivable 做更新操作
        tierCashDeposit.setId(id);      // 这个只插入一条数据，id 和 instanceId 都设置一样，后面好查找
        tierCashDeposit.setInstanceId(id);
        tierCashDepositMapper.insertTierCashDeposit(tierCashDeposit);

        AnnualReviewy annualReviewy = new AnnualReviewy();
        annualReviewy.setId(id);
        annualReviewy.setInstanceId(processInstance.getId());
        annualReviewy.setTitle(title);
        // annualReviewy.setType();  // TODO 待确认，先不填
        annualReviewy.setCreateTime(DateUtils.getNowDate());
        annualReviewy.setState("0");
        annualReviewy.setCreateName(SecurityUtils.getNickName());
        annualReviewy.setCreateBy(SecurityUtils.getUsername());
        annualReviewy.setCreateTime(DateUtils.getNowDate());
        // annualReviewy.setUsername(); // TODO 先不填

        return annualReviewyMapper.insertAnnualReviewy(annualReviewy);
    }

    /**
     * 修改feike
     *
     * @param tierCashDeposit feike
     * @return 结果
     */
    @Override
    public int updateTierCashDeposit(TierCashDeposit tierCashDeposit) {
        System.out.println("tierCashDeposit修改对象： " + tierCashDeposit);
        return tierCashDepositMapper.updateTierCashDeposit(tierCashDeposit);
    }

    /**
     * 批量删除feike
     *
     * @param ids 需要删除的feikeID
     * @return 结果
     */
    @Override
    public int deleteTierCashDepositByIds(String[] ids) {
        System.out.println("tierCashDeposit删除对象： " + ids);
        List<AnnualReviewy> annualReviewyList = annualReviewyMapper.selectAnnualReviewyByIds(ids);
        int num = 0;
        if (annualReviewyList != null && annualReviewyList.size() > 0) {
            for (AnnualReviewy annualReviewy : annualReviewyList) {
                int i = tierCashDepositMapper.deleteTierCashDepositById(annualReviewy.getId());
                if (i == 0) {
                    return 0;
                } else {
                    num = num + 1;
                    return annualReviewyMapper.deleteAnnualReviewyById(annualReviewy.getId());
                }

            }
        }
        return num;

    }

    /**
     * 删除feike信息
     *
     * @param id feikeID
     * @return 结果
     */
    @Override
    public int deleteTierCashDepositById(String id) {
        return tierCashDepositMapper.deleteTierCashDepositById(id);
    }

    @Override
    public List<AnnualReviewyHistoryVO> selectTierCashDepositListAll(AnnualReviewy annualReviewy, TierCashDeposit tierCashDeposit) {
        return tierCashDepositMapper.selectTierCashDepositListBySelf(annualReviewy, tierCashDeposit, SecurityUtils.getLoginUser()
                                                                                                                  .getUser()
                                                                                                                  .getDeptId());
    }

    @Override
    public Map<String, Object> selectTierCashDepositBy(Map<String, Object> map) {
        System.out.println("tierCashDeposit==" + map);
        List<Map<String, Object>> dealerList = (List<Map<String, Object>>) map.get("dealerList");
        Map<String, Object> parkingLocationMap = new HashMap<>();
        List<ParkingLocation> parkingLocationList=null;
        if (dealerList != null && dealerList.size() > 0) {
            for (Map<String, Object> dealerObj : dealerList) {
                String dealerName = (String) dealerObj.get("dealerName");
                // 根据groupId和dealerId获取详细信息
                // TierCashDeposit tierCashDeposit=tierCashDepositMapper.selectTiierCashDepositByDealerName(dealerName);
               parkingLocationList = parkingLocationRegistrationMapper.selectParkingLocationRegistrationByDealerName(dealerName);

            }
        }
        System.out.println("parkingLocationMap==" + parkingLocationList);
        return parkingLocationMap;

    }

    @Override
    public List<TierCashDeposit> selectTierCashDepositByDralerName(String dealerName) {
        System.out.println("tierCashDeposit==" + dealerName);
        List<TierCashDeposit>  tierCashDepositList=null;
        if (!StringUtils.isEmpty(dealerName)){
            List<ParkingLocation> parkingLocationList= parkingLocationRegistrationMapper.selectParkingLocationRegistrationByDealerName(dealerName);

            if (parkingLocationList!=null&&parkingLocationList.size()>0){
                for (ParkingLocation parkingLocation : parkingLocationList) {
                    TierCashDeposit tierCashDeposit = new TierCashDeposit();
                    tierCashDeposit.setInstanceId(parkingLocation.getInstanceId());
                    tierCashDeposit.setDearler(parkingLocation.getDealernamecn());
                    tierCashDeposit.setDealerNameCn(parkingLocation.getDealernamecn());
                    tierCashDeposit.setStatus(parkingLocation.getStatus());
                    tierCashDeposit.setParkingLocation(parkingLocation.getParkinglocation());
                    // tierCashDeposit.setNotes(parkingLocation.getNotes());
                    tierCashDepositList.add(tierCashDeposit);
                }
            }
        }
        return tierCashDepositList;
    }

    @Override
    public List<ParkingLocationVO1> selectTierCashDepositLists() {
        List<ParkingLocation> parkingLocationList = parkingLocationMapper.selectParkingLocationLists();
        System.out.println("parkingLocationList列表=="+parkingLocationList);
        List<ParkingLocationVO1> parkingLocationVO1s=new ArrayList<>();
        if(parkingLocationList!=null&&parkingLocationList.size()>0){
            for (ParkingLocation parkingLocation : parkingLocationList) {
                ParkingLocationVO1 parkingLocationVO1 = new ParkingLocationVO1();
                BeanUtils.copyProperties(parkingLocation,parkingLocationVO1);
                String parkinglocation1 = parkingLocation.getParkinglocation();
                // String[] split = parkinglocation1.split(",");
                // parkingLocationVO1.setParkinglocations(split);

                parkingLocationVO1.setParkinglocation(parkinglocation1);
                // parkingLocationVO1.setTierDepositReceivable(parkinglocation1);
                // parkingLocationVO1.setTierDepositGap(parkinglocation1);

                List dealerCodeList=new ArrayList();
                String status = parkingLocation.getStatus();
                Map<String,Object> map = parkingLocationMapper.selectParkingLocationCountAndSumByType(parkingLocation.getDealernamecn(),parkingLocation.getType(),status);
                System.out.println("map===="+map);
                Object registeredTwoTierNumber =  map.get("registeredTwoTierNumber");
                Object twoTierWithDesposit = map.get("twoTierWithDesposit");
                System.out.println("registeredTwoTierNumber=="+registeredTwoTierNumber);
                System.out.println("twoTierWithDesposit=="+twoTierWithDesposit);
                String s1="0";
                String s2="0";
                if(registeredTwoTierNumber!=null){
                    s1 = String.valueOf(registeredTwoTierNumber);
                }
                if(twoTierWithDesposit!=null){
                    s2 = String.valueOf(twoTierWithDesposit);
                }

                parkingLocationVO1.setRegisteredTwoTierNumber(new BigDecimal(s1));
                parkingLocationVO1.setTwoTierWithDesposit(new BigDecimal(s2));

                List<DealerInformation> dealerInformationList = dealerInformationMapper.selectDealerInformationByDealerName(parkingLocation.getDealernamecn());
                System.out.println("dealerInformationList列表=="+dealerInformationList);
                if(dealerInformationList!=null&&dealerInformationList.size()>0){
                    for (DealerInformation dealerInformation : dealerInformationList) {
                        String dealerCode = dealerInformation.getDealerCode();
                        parkingLocationVO1.setGroupName(dealerInformation.getGroupName());
                        dealerCodeList.add(dealerCode);
                    }
                }
                Plm plm = plmMapper.selectPlmListByDealerName(parkingLocation.getDealernamecn());
                Long permitted2ndtierwithdesposit = plm.getPermitted2ndtierwithdesposit();
                Long permitted2ndtierwithoutdesposit = plm.getPermitted2ndtierwithoutdesposit();
                parkingLocationVO1.setDealercCodes(dealerCodeList);
                parkingLocationVO1.setPermitted2ndTierWithDesposit(permitted2ndtierwithdesposit);
                parkingLocationVO1.setPermitted2ndTierWithoutDesposit(permitted2ndtierwithoutdesposit);
                parkingLocationVO1s.add(parkingLocationVO1);
                System.out.println("parkingLocation返回的数据=="+parkingLocation);
            }
        }
        System.out.println("parkingLocationVO1s列表=="+parkingLocationVO1s);
        return parkingLocationVO1s;
    }
}
